import os
if os.getenv('AG_ENV_PYTHON_PATH') is None:
    ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) + os.sep
else:
    ROOT_DIR = os.getcwd() + os.sep
    # ROOT_DIR = WORK_DIR + "ag_art" + os.sep
parent_dir = os.path.dirname(ROOT_DIR)
import importlib.util
abstractjob_path = parent_dir+'/SKO/AbstractDPJob.py'
spec = importlib.util.spec_from_file_location('AbstractDPJob', abstractjob_path)
abstractjob_module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(abstractjob_module)
AbstractDPJob = abstractjob_module.AbstractDPJob

pso_path = parent_dir+'/SKO/PSO.py'
spec2 = importlib.util.spec_from_file_location('PSO', pso_path)
pso_module = importlib.util.module_from_spec(spec2)
spec2.loader.exec_module(pso_module)
PSO = pso_module.PSO


# from SKO.AbstractDPJob import AbstractDPJob
import sys, datetime, json, logging, os, time, math
import pandas as pd
import numpy as np
from numpy import array
import cvxpy as cp
# from SKO.PSO import PSO
import datetime
from sqlalchemy import create_engine
from sqlalchemy.pool import NullPool
import os
class OptimalJob(AbstractDPJob):



    def __init__(self,
                 p_tmpl_no=None, p_price_sql=None):
        super(OptimalJob, self).__init__()
        self.tmpl_no = p_tmpl_no
        self.price_sql = p_price_sql
        pass


    def execute(self):
        return self.do_execute()


    def do_execute(self):

        super(OptimalJob, self).do_execute()
        """
        通过JSON传入参数
        """
        # start = datetime.datetime.now()

        # row_data = self.body_dict
        # tmpl_no = row_data['tmpl_no']
        # price_sql = row_data['price_sql']
        tmpl_no = self.tmpl_no
        price_sql = self.price_sql
        # 数据库配置写死
        DB_HOST_MPP_DB2 = '10.70.48.41'
        DB_PORT_MPP_DB2 = 50021
        DB_DBNAME_MPP_DB2 = 'BGBDPROD'
        DB_USER_MPP_DB2 = 'g0mazzai'
        DB_PASSWORD_MPP_DB2 = 'g0mazzaibg00'

        # 数据库连接函数写死
        def getConnectionDb2(host, port, dbname, user, password):
            # conn = pg.connect(host=host, port=port, dbname=dbname, user=user, password=password)
            engine = create_engine('ibm_db_sa://' + user + ':' + password + '@' + host + ':' + str(port) + '/' + dbname,
                                   encoding="utf-8", poolclass=NullPool)
            return engine.connect()

        db_conn_mpp = getConnectionDb2(DB_HOST_MPP_DB2,
                                       DB_PORT_MPP_DB2,
                                       DB_DBNAME_MPP_DB2,
                                       DB_USER_MPP_DB2,
                                       DB_PASSWORD_MPP_DB2)
        # PSO的参数
        w = 0.8  # 惯性因子，一般取1
        c1 = 2  # 学习因子，一般取2
        c2 = 2  #
        # dim = 20  # 维度的维度
        size = 100  # 种群大小，即种群中小鸟的个数
        iter_num = 100  # 算法最大迭代次数
        # max_vel = 0.5  # 限制粒子的最大速度
        max_vel = 1
        # 配置参数
        max_constant = 100000
        min_constant = 0
        ###fix_code
        # price_1_3_1=0
        # price_2_3_1=0
        # price_3_2_1=0
        # 写死JSON传入变量
        # tmpl_no = 'TM202308181451'
        # price_sql = " select * " \
        #             " from BG00MAZZAI.T_ADS_WH_YLMX_MANUALPRICE_INFO " \
        #             " where TMPL_NO ='%s' " % (tmpl_no)
        # 读数据库数据
        sql = " select * " \
              " from BG00MAZZAI.T_ADS_WH_YLMX_COALKIND_INFO " \
              " where TMPL_NO ='%s' " % (tmpl_no)
        data_meizhong = pd.read_sql_query(sql, con=db_conn_mpp)
        # data_meizhong = pd.read_excel('模型煤种配置表.xlsx')
        data_meizhong.columns = data_meizhong.columns.str.upper()
        # data_meizhong = data_meizhong[data_meizhong['TMPL_NO'] == tmpl_no]
        sql = " select * " \
              " from BG00MAZZAI.T_ADS_WH_YLMX_PRECOND_INFO " \
              " where TMPL_NO ='%s' " % (tmpl_no)
        data_qianti = pd.read_sql_query(sql, con=db_conn_mpp)
        # data_qianti = pd.read_excel('前提条件配置表.xlsx')
        data_qianti.columns = data_qianti.columns.str.upper()
        sql = " select * " \
              " from BG00MAZZAI.T_ADS_WH_YLMX_MAINPARM_INFO " \
              " where TMPL_NO ='%s' " % (tmpl_no)
        data_zhuyao = pd.read_sql_query(sql, con=db_conn_mpp)
        # data_zhuyao = pd.read_excel('主要参数配置表.xlsx')
        data_zhuyao.columns = data_zhuyao.columns.str.upper()
        sql = " select * " \
              " from BG00MAZZAI.T_ADS_WH_YLMX_INVLIMIT_INFO " \
              " where TMPL_NO ='%s' " % (tmpl_no)
        data_bilikegong = pd.read_sql_query(sql, con=db_conn_mpp)
        # data_bilikegong = pd.read_excel('煤比例可供资源配置表.xlsx')
        data_bilikegong.columns = data_bilikegong.columns.str.upper()
        sql = " select * " \
              " from BG00MAZZAI.T_ADS_WH_YLMX_IND_INFO " \
              " where TMPL_NO ='%s' " % (tmpl_no)
        data_meizhi = pd.read_sql_query(sql, con=db_conn_mpp)
        # data_meizhi = pd.read_excel('煤质信息配置表.xlsx')
        data_meizhi.columns = data_meizhi.columns.str.upper()
        sql = " select * " \
              " from BG00MAZZAI.T_ADS_WH_YLMX_VARINDLIMIT_INFO " \
              " where TMPL_NO ='%s' " % (tmpl_no)
        data_shangxiaxian = pd.read_sql_query(sql, con=db_conn_mpp)
        # data_shangxiaxian = pd.read_excel('煤质上下限配置表.xlsx')
        data_shangxiaxian.columns = data_shangxiaxian.columns.str.upper()
        sql = price_sql
        data_price = pd.read_sql_query(sql, con=db_conn_mpp)
        # data_price = pd.read_excel('手工价格配置表.xlsx')
        data_price.columns = data_price.columns.str.upper()
        # 数据处理，不要外购焦粉
        # data_meizhong = data_meizhong[(data_meizhong['BIG_VAR'] != '烧结煤') | (data_meizhong['VAR'] != '焦粉')]
        data_meizhong = data_meizhong.reset_index(drop=True)
        data0 = data_meizhong.copy()
        data0.drop(['REC_ID'], axis=1, inplace=True)
        data0.drop(['TMPL_NO'], axis=1, inplace=True)
        data0.drop(['REC_CREATE_TIME'], axis=1, inplace=True)
        data0.drop(['REC_CREATOR'], axis=1, inplace=True)
        data0.drop(['REC_REVISE_TIME'], axis=1, inplace=True)
        data0.drop(['REC_REVISOR'], axis=1, inplace=True)
        row_count = data0.shape[0]

        # print("行数：", row_count)
        def __cal_rank_pinzhong(x):
            rst = 0
            if x.BIG_VAR == '喷吹煤':
                rst = 1
            elif x.BIG_VAR == '发电煤':
                rst = 2
            elif x.BIG_VAR == '烧结煤':
                rst = 3
            return rst

        data0['pinzhong'] = data0.apply(lambda x: __cal_rank_pinzhong(x), axis=1)

        def __cal_rank_xingzhuang(x):
            rst = 0
            if x.BIG_VAR == '喷吹煤':
                if x.VAR == '烟煤':
                    rst = 1
                elif x.VAR == '无烟煤':
                    rst = 2
                elif x.VAR == '兰炭':
                    rst = 3
            elif x.BIG_VAR == '发电煤':
                if x.VAR == '大同类':
                    rst = 1
                elif x.VAR == '神府类':
                    rst = 2
                elif x.VAR == '兰炭类':
                    rst = 3
            elif x.BIG_VAR == '烧结煤':
                if x.VAR == '无烟煤':
                    rst = 1
                elif x.VAR == '兰炭':
                    rst = 2
                elif x.VAR == '焦粉':
                    rst = 3
            return rst

        data0['xingzhuang'] = data0.apply(lambda x: __cal_rank_xingzhuang(x), axis=1)

        def __cal_rank_group(x):
            rst = str(x.pinzhong) + '_' + str(x.xingzhuang)
            return rst

        data0['group'] = data0.apply(lambda x: __cal_rank_group(x), axis=1)
        data0 = data0.reset_index(drop=False)
        data0.rename(columns={'index': 'index_old'}, inplace=True)

        data0['rank0'] = data0['index_old'].groupby(data0['group']).rank()
        data0['pinming'] = data0['rank0'].astype(int)

        def __cal_rank_mark(x):
            rst = str(x.group) + '_' + str(x.pinming)
            return rst

        data0['mark'] = data0.apply(lambda x: __cal_rank_mark(x), axis=1)
        # data0.drop(['group'], axis=1, inplace=True)
        data0.drop(['rank0'], axis=1, inplace=True)
        # 生成mark列拼接动态参数
        # 统计个数，做个var_df以便后续对应
        big_var_list = ['喷吹煤', '发电煤', '烧结煤']
        var_list1 = ['烟煤', '无烟煤', '兰炭']
        var_list2 = ['大同类', '神府类', '兰炭类']
        var_list3 = ['无烟煤', '兰炭', '焦粉']
        var_df = pd.DataFrame(columns=['BIG_VAR', 'VAR', 'group', 'count'])
        dict = {}
        # var_list = []
        ldict = {}
        for i in range(1, len(big_var_list) + 1):
            # print(i)
            # exec('var_list =var_list{}'.format(i))
            exec('var_list =var_list{}'.format(i), locals(), ldict)
            var_list = ldict["var_list"]
            # print(var_list)
            for j in range(1, len(var_list) + 1):
                # print(j)
                df = data_meizhong[
                    (data_meizhong['BIG_VAR'] == big_var_list[i - 1]) & (data_meizhong['VAR'] == var_list[j - 1])]
                row_count = df.shape[0]
                # print("行数：", row_count)
                dict['BIG_VAR'] = big_var_list[i - 1]
                dict['VAR'] = var_list[j - 1]
                dict['group'] = str(i) + '_' + str(j)
                dict['count'] = row_count
                new_row = pd.Series(dict)
                var_df = var_df.append(new_row, ignore_index=True)
        # print('finish')
        # #动态变量测试
        ###价格
        data_price.rename(columns={'UNIT_PRICE': 'PRICE'}, inplace=True)
        data_price = data_price[['PROD_DSCR', 'PRICE']]
        v = ['PROD_DSCR']
        df3_price = pd.merge(data0, data_price, on=v, how='left')
        df3_price.PRICE.fillna(max_constant, inplace=True)
        for index, row in df3_price.iterrows():
            exec('price_{} ={}'.format(row['mark'], row['PRICE']))
            # exec('print(price_{})'.format(row['mark']))
        ###可控资源
        data_bilikegong.rename(columns={'INV_WT': 'WT'}, inplace=True)
        data_bilikegong_1 = data_bilikegong[data_bilikegong['FLAG'] == '品名']
        data_bilikegong_1 = data_bilikegong_1.reset_index(drop=True)
        data_bilikegong_1 = data_bilikegong_1[['PROD_DSCR', 'WT']]
        v = ['PROD_DSCR']
        df3 = pd.merge(data0, data_bilikegong_1, on=v, how='left')
        # 可供资源为空，无穷大库存
        df3.WT.fillna(max_constant, inplace=True)
        for index, row in df3.iterrows():
            exec('kegongziyuan_{} ={}'.format(row['mark'], row['WT']))
        ###比例上下限
        data_bilikegong.rename(columns={'MAX_VALUE': 'UL'}, inplace=True)
        data_bilikegong.rename(columns={'MIN_VALUE': 'LL'}, inplace=True)
        data_bilikegong_1 = data_bilikegong[data_bilikegong['FLAG'] == '品名']
        data_bilikegong_1 = data_bilikegong_1.reset_index(drop=True)
        data_bilikegong_1 = data_bilikegong_1[['PROD_DSCR', 'UL', 'LL']]
        v = ['PROD_DSCR']
        df3 = pd.merge(data0, data_bilikegong_1, on=v, how='left')
        # 比例0-100
        df3.UL.fillna(100, inplace=True)
        df3.LL.fillna(0, inplace=True)

        for index, row in df3.iterrows():
            exec('ul_{} ={}'.format(row['mark'], row['UL']))
            exec('ll_{} ={}'.format(row['mark'], row['LL']))
        data_bilikegong_2 = data_bilikegong[data_bilikegong['FLAG'] == '性状']
        data_bilikegong_2 = data_bilikegong_2.reset_index(drop=True)
        def __cal_new_var(x):
            rst = str(x.BIG_VAR) + '_' + str(x.VAR)
            return rst
        data_bilikegong_2['NEW_VAR'] = data_bilikegong_2.apply(lambda x: __cal_new_var(x), axis=1)
        data_bilikegong_2 = data_bilikegong_2[['NEW_VAR', 'UL', 'LL']]
        var_df1 = var_df.copy()
        def __cal_new_var(x):
            rst = str(x.BIG_VAR) + '_' + str(x.VAR)
            return rst
        var_df1['NEW_VAR'] = var_df1.apply(lambda x: __cal_new_var(x), axis=1)
        v = ['NEW_VAR']
        # print(var_df1)
        # print(data_bilikegong_2)
        df3 = pd.merge(var_df1, data_bilikegong_2, on=v, how='left')
        # print(df3)
        # 比例0-100
        df3.UL.fillna(100, inplace=True)
        df3.LL.fillna(0, inplace=True)
        for index, row in df3.iterrows():
            exec('ul_{} ={}'.format(row['group'], row['UL']))
            exec('ll_{} ={}'.format(row['group'], row['LL']))
        ###煤质
        data_meizhi.rename(columns={'H2O': 'shui'}, inplace=True)
        data_meizhi.rename(columns={'ASH': 'hui'}, inplace=True)
        data_meizhi.rename(columns={'COKE_VM': 'huifa'}, inplace=True)
        data_meizhi.rename(columns={'S': 'liu'}, inplace=True)
        data_meizhi.rename(columns={'COKE_FIXCARBON': 'gu'}, inplace=True)
        data_meizhi.rename(columns={'WEAR_ERROR_FLAG': 'mo'}, inplace=True)
        data_meizhi.rename(columns={'COKE_HOTVALUE': 're'}, inplace=True)
        data_meizhi.rename(columns={'C': 'cc'}, inplace=True)

        data_meizhi_1 = data_meizhi[['PROD_DSCR', 'shui', 'hui', 'huifa', 'liu', 'gu', 'mo', 're', 'cc']]
        v = ['PROD_DSCR']
        df3 = pd.merge(data0, data_meizhi_1, on=v, how='left')
        df3.fillna(max_constant, inplace=True)
        for index, row in df3.iterrows():
            exec('shui_{} ={}'.format(row['mark'], row['shui']))
            exec('hui_{} ={}'.format(row['mark'], row['hui']))
            exec('huifa_{} ={}'.format(row['mark'], row['huifa']))
            exec('liu_{} ={}'.format(row['mark'], row['liu']))
            exec('gu_{} ={}'.format(row['mark'], row['gu']))
            exec('mo_{} ={}'.format(row['mark'], row['mo']))
            exec('re_{} ={}'.format(row['mark'], row['re']))
            exec('cc_{} ={}'.format(row['mark'], row['cc']))
        ###煤质上下限
        data_shangxiaxian_1 = data_shangxiaxian[
            (data_shangxiaxian['FLAG'] == '上限') & (data_shangxiaxian['BIG_VAR'] == '喷吹煤')]
        data_shangxiaxian_1 = data_shangxiaxian_1.reset_index(drop=True)
        data_shangxiaxian_1.fillna(max_constant, inplace=True)
        penchui_shui_ul = data_shangxiaxian_1.loc[0]['H2O']
        penchui_hui_ul = data_shangxiaxian_1.loc[0]['ASH']
        penchui_huifa_ul = data_shangxiaxian_1.loc[0]['COKE_VM']
        penchui_liu_ul = data_shangxiaxian_1.loc[0]['S']
        penchui_gu_ul = data_shangxiaxian_1.loc[0]['COKE_FIXCARBON']
        penchui_mo_ul = data_shangxiaxian_1.loc[0]['WEAR_ERROR_FLAG']
        penchui_re_ul = data_shangxiaxian_1.loc[0]['COKE_HOTVALUE']
        penchui_cc_ul = data_shangxiaxian_1.loc[0]['C']
        data_shangxiaxian_1 = data_shangxiaxian[
            (data_shangxiaxian['FLAG'] == '下限') & (data_shangxiaxian['BIG_VAR'] == '喷吹煤')]
        data_shangxiaxian_1 = data_shangxiaxian_1.reset_index(drop=True)
        data_shangxiaxian_1.fillna(min_constant, inplace=True)

        penchui_shui_ll = data_shangxiaxian_1.loc[0]['H2O']
        penchui_hui_ll = data_shangxiaxian_1.loc[0]['ASH']
        penchui_huifa_ll = data_shangxiaxian_1.loc[0]['COKE_VM']
        penchui_liu_ll = data_shangxiaxian_1.loc[0]['S']
        penchui_gu_ll = data_shangxiaxian_1.loc[0]['COKE_FIXCARBON']
        penchui_mo_ll = data_shangxiaxian_1.loc[0]['WEAR_ERROR_FLAG']
        penchui_re_ll = data_shangxiaxian_1.loc[0]['COKE_HOTVALUE']
        penchui_cc_ll = data_shangxiaxian_1.loc[0]['C']
        data_shangxiaxian_1 = data_shangxiaxian[
            (data_shangxiaxian['FLAG'] == '上限') & (data_shangxiaxian['BIG_VAR'] == '发电煤')]
        data_shangxiaxian_1 = data_shangxiaxian_1.reset_index(drop=True)
        data_shangxiaxian_1.fillna(max_constant, inplace=True)

        fadian_shui_ul = data_shangxiaxian_1.loc[0]['H2O']
        fadian_hui_ul = data_shangxiaxian_1.loc[0]['ASH']
        fadian_huifa_ul = data_shangxiaxian_1.loc[0]['COKE_VM']
        fadian_liu_ul = data_shangxiaxian_1.loc[0]['S']
        fadian_gu_ul = data_shangxiaxian_1.loc[0]['COKE_FIXCARBON']
        fadian_mo_ul = data_shangxiaxian_1.loc[0]['WEAR_ERROR_FLAG']
        fadian_re_ul = data_shangxiaxian_1.loc[0]['COKE_HOTVALUE']
        fadian_cc_ul = data_shangxiaxian_1.loc[0]['C']
        data_shangxiaxian_1 = data_shangxiaxian[
            (data_shangxiaxian['FLAG'] == '下限') & (data_shangxiaxian['BIG_VAR'] == '发电煤')]
        data_shangxiaxian_1 = data_shangxiaxian_1.reset_index(drop=True)
        data_shangxiaxian_1.fillna(min_constant, inplace=True)

        fadian_shui_ll = data_shangxiaxian_1.loc[0]['H2O']
        fadian_hui_ll = data_shangxiaxian_1.loc[0]['ASH']
        fadian_huifa_ll = data_shangxiaxian_1.loc[0]['COKE_VM']
        fadian_liu_ll = data_shangxiaxian_1.loc[0]['S']
        fadian_gu_ll = data_shangxiaxian_1.loc[0]['COKE_FIXCARBON']
        fadian_mo_ll = data_shangxiaxian_1.loc[0]['WEAR_ERROR_FLAG']
        fadian_re_ll = data_shangxiaxian_1.loc[0]['COKE_HOTVALUE']
        fadian_cc_ll = data_shangxiaxian_1.loc[0]['C']
        data_shangxiaxian_1 = data_shangxiaxian[
            (data_shangxiaxian['FLAG'] == '上限') & (data_shangxiaxian['BIG_VAR'] == '烧结煤')]
        data_shangxiaxian_1 = data_shangxiaxian_1.reset_index(drop=True)
        data_shangxiaxian_1.fillna(max_constant, inplace=True)

        shaojie_shui_ul = data_shangxiaxian_1.loc[0]['H2O']
        shaojie_hui_ul = data_shangxiaxian_1.loc[0]['ASH']
        shaojie_huifa_ul = data_shangxiaxian_1.loc[0]['COKE_VM']
        shaojie_liu_ul = data_shangxiaxian_1.loc[0]['S']
        shaojie_gu_ul = data_shangxiaxian_1.loc[0]['COKE_FIXCARBON']
        shaojie_mo_ul = data_shangxiaxian_1.loc[0]['WEAR_ERROR_FLAG']
        shaojie_re_ul = data_shangxiaxian_1.loc[0]['COKE_HOTVALUE']
        shaojie_cc_ul = data_shangxiaxian_1.loc[0]['C']
        data_shangxiaxian_1 = data_shangxiaxian[
            (data_shangxiaxian['FLAG'] == '下限') & (data_shangxiaxian['BIG_VAR'] == '烧结煤')]
        data_shangxiaxian_1 = data_shangxiaxian_1.reset_index(drop=True)
        data_shangxiaxian_1.fillna(min_constant, inplace=True)

        shaojie_shui_ll = data_shangxiaxian_1.loc[0]['H2O']
        shaojie_hui_ll = data_shangxiaxian_1.loc[0]['ASH']
        shaojie_huifa_ll = data_shangxiaxian_1.loc[0]['COKE_VM']
        shaojie_liu_ll = data_shangxiaxian_1.loc[0]['S']
        shaojie_gu_ll = data_shangxiaxian_1.loc[0]['COKE_FIXCARBON']
        shaojie_mo_ll = data_shangxiaxian_1.loc[0]['WEAR_ERROR_FLAG']
        shaojie_re_ll = data_shangxiaxian_1.loc[0]['COKE_HOTVALUE']
        shaojie_cc_ll = data_shangxiaxian_1.loc[0]['C']

        # 年度前提条件表
        kongmeizhibiao = data_qianti.loc[0]['TOTAL_COAL_AMT']
        tieshuichanliang = data_qianti.loc[0]['MOLTIRON_WT']
        jiaotanchanliang = data_qianti.loc[0]['COKE_OUTPUT']
        fadianliang = data_qianti.loc[0]['ELECOUT']
        shaojiechanliang = data_qianti.loc[0]['SINTER_OUTPUT']
        zongmeibi = data_qianti.loc[0]['BF_PCR']
        CDQbi = data_qianti.loc[0]['CDQ_RATE']

        # 纯煤比 = 总煤比 - CDQ比
        chunmeibi = data_qianti.loc[0]['BF_PCR1']
        zongjiaobi = data_qianti.loc[0]['BF_CR']
        shaojieranliaobi = data_qianti.loc[0]['SINTER_FUEL_RATIO']
        # 主要参数表
        chengjiaolv = data_zhuyao.loc[0]['COKING_COKEYR']
        yejinjiaolv = data_zhuyao.loc[0]['COKING_METCOKRAT']
        cujiaolv = data_zhuyao.loc[0]['SINTER_CRSCOKE_RATIO']
        meidianbi = data_zhuyao.loc[0]['COAL_ELEC_RATIO']
        fadianmeihao = data_zhuyao.loc[0]['COAL_USE']
        lianjiaomeishuifen = data_zhuyao.loc[0]['COKING_COALBLD_MOIST']
        penchuimeishuifen = data_zhuyao.loc[0]['BF_COALINJECT_MOIST']
        shaojiemeishuifen = data_zhuyao.loc[0]['SINTER_COAL_MOIST']
        meitanwushunlv = data_zhuyao.loc[0]['COAL_LOSS_RATE']
        waigoujiaoshuifen = data_zhuyao.loc[0]['PCOKE_MOIST']
        waigoujiaofenlv = data_zhuyao.loc[0]['PCOKE_COKEPOWD_RATE']
        shaojiejiaofenshuifen = data_zhuyao.loc[0]['SINTER_COKE_MOIST']
        lantanshuifen = data_zhuyao.loc[0]['SEMICOKE_MOIST']
        jiaotanchaochanlv = data_zhuyao.loc[0]['COKING_OVERPROD_RATE']

        # print('参数读取完毕！！')
        ############################
        # 参数读取完毕
        # 炼焦煤
        CAL_WT_lianjiaomei = jiaotanchanliang / chengjiaolv * 100 / (100 - lianjiaomeishuifen) * 100 * (
                    100 + meitanwushunlv) / 100
        WT_lianjiaomei = CAL_WT_lianjiaomei * (100 + jiaotanchaochanlv) / 100
        # 外购焦炭    （补炼焦煤）
        WT_waigoujiaotan = (tieshuichanliang * zongjiaobi / 1000 - jiaotanchanliang * yejinjiaolv / 100) / (
                    100 - waigoujiaofenlv) * 100 / (100 - waigoujiaoshuifen) * 100

        # 构建配置系数df
        coef_df = pd.DataFrame(columns=['mark'])
        dict = {}
        data0_1 = data0[(data0['BIG_VAR'] == '喷吹煤') & (data0['VAR'] == '烟煤')]
        data0_1 = data0_1.reset_index(drop=True)
        for index, row in data0_1.iterrows():
            exec("dict['mark'] = '{}'".format(row['mark']))
            new_row = pd.Series(dict)
            coef_df = coef_df.append(new_row, ignore_index=True)
        data0_1 = data0[(data0['BIG_VAR'] == '喷吹煤') & (data0['VAR'] == '无烟煤')]

        data0_1 = data0_1.reset_index(drop=True)
        for index, row in data0_1.iterrows():
            exec("dict['mark'] = '{}'".format(row['mark']))
            new_row = pd.Series(dict)
            coef_df = coef_df.append(new_row, ignore_index=True)
        data0_1 = data0[(data0['BIG_VAR'] == '发电煤') & (data0['VAR'] == '大同类')]

        data0_1 = data0_1.reset_index(drop=True)
        for index, row in data0_1.iterrows():
            exec("dict['mark'] = '{}'".format(row['mark']))
            new_row = pd.Series(dict)
            coef_df = coef_df.append(new_row, ignore_index=True)
        data0_1 = data0[(data0['BIG_VAR'] == '发电煤') & (data0['VAR'] == '神府类')]

        data0_1 = data0_1.reset_index(drop=True)
        for index, row in data0_1.iterrows():
            exec("dict['mark'] = '{}'".format(row['mark']))
            new_row = pd.Series(dict)
            coef_df = coef_df.append(new_row, ignore_index=True)
        data0_1 = data0[(data0['BIG_VAR'] == '烧结煤') & (data0['VAR'] == '无烟煤')]

        data0_1 = data0_1.reset_index(drop=True)
        for index, row in data0_1.iterrows():
            exec("dict['mark'] = '{}'".format(row['mark']))
            new_row = pd.Series(dict)
            coef_df = coef_df.append(new_row, ignore_index=True)
        data0_1 = data0[(data0['BIG_VAR'] == '喷吹煤') & (data0['VAR'] == '兰炭')]

        data0_1 = data0_1.reset_index(drop=True)
        for index, row in data0_1.iterrows():
            exec("dict['mark'] = '{}'".format(row['mark']))
            new_row = pd.Series(dict)
            coef_df = coef_df.append(new_row, ignore_index=True)
        data0_1 = data0[(data0['BIG_VAR'] == '发电煤') & (data0['VAR'] == '兰炭类')]

        data0_1 = data0_1.reset_index(drop=True)
        for index, row in data0_1.iterrows():
            exec("dict['mark'] = '{}'".format(row['mark']))
            new_row = pd.Series(dict)
            coef_df = coef_df.append(new_row, ignore_index=True)
        data0_1 = data0[(data0['BIG_VAR'] == '烧结煤') & (data0['VAR'] == '兰炭') & (data0['VAR'] == '焦粉')]

        data0_1 = data0_1.reset_index(drop=True)
        for index, row in data0_1.iterrows():
            exec("dict['mark'] = '{}'".format(row['mark']))
            new_row = pd.Series(dict)
            coef_df = coef_df.append(new_row, ignore_index=True)
        mark_list = coef_df['mark'].to_list()
        # len1不包括兰炭的煤种个数
        data0_1 = data0[(data0['VAR'] != '兰炭类') & (data0['VAR'] != '兰炭') & (data0['VAR'] != '焦粉')]
        data0_1 = data0_1.reset_index(drop=True)
        len1 = len(data0_1)

        a11 = (100 - penchuimeishuifen) / 100 / (100 + meitanwushunlv) * 100
        a12 = (100 - lantanshuifen) / 100
        a21 = 1
        a22 = 1
        a31 = (100 - shaojiemeishuifen) / 100 / (100 + meitanwushunlv) * 100
        a32 = (100 - shaojiejiaofenshuifen) / 100
        b0 = kongmeizhibiao - WT_lianjiaomei
        b1 = tieshuichanliang * chunmeibi / 1000
        b2 = fadianliang * meidianbi / 100 * fadianmeihao / 100 * (100 + meitanwushunlv) / 100
        b3 = shaojiechanliang * shaojieranliaobi / 1000 - jiaotanchanliang * cujiaolv / 100 - WT_waigoujiaotan * waigoujiaofenlv / 100 * (
                100 - waigoujiaoshuifen) / 100
        # 构建所有参数的df
        canshu_df = pd.DataFrame(columns=['编号', '参数名', '步骤', 'mark', 'group', 'big_var', 'meizhi'])
        dict_canshu = {}
        j_start = 0
        # 必要条件，控煤指标
        array_len = len(mark_list)
        import numpy as np
        from numpy import array
        y0 = array([[0] * array_len], dtype=float)
        for i in range(0, int(len1)):
            y0[0, i] = 1
        m0 = array([b0])
        n0 = array([b0])
        dict_canshu['编号'] = 0
        dict_canshu['参数名'] = '控煤指标'
        dict_canshu['步骤'] = '前提条件'
        new_row = pd.Series(dict_canshu)
        canshu_df = canshu_df.append(new_row, ignore_index=True)
        dict_canshu = {}
        j_start = j_start + 1
        # 可供资源
        for j in range(j_start, j_start + int(array_len)):
            exec('y{} = array([[0] * array_len],dtype=float)'.format(j))
            exec('y{}[0,j-j_start] = 1'.format(j))
            mark_tmp = mark_list[j - 1]
            exec('m{} = array([kegongziyuan_{}])'.format(j, mark_tmp))
            exec('n{} = array([max_constant])'.format(j))
            dict_canshu['编号'] = j
            dict_canshu['参数名'] = '可供资源'
            if mark_tmp[0] == '1':
                buzhou_tmp = '喷吹煤'
            elif mark_tmp[0] == '2':
                buzhou_tmp = '发电煤'
            elif mark_tmp[0] == '3':
                buzhou_tmp = '烧结煤'
            dict_canshu['步骤'] = buzhou_tmp
            dict_canshu['mark'] = mark_tmp
            new_row = pd.Series(dict_canshu)
            canshu_df = canshu_df.append(new_row, ignore_index=True)
            dict_canshu = {}
        j_start = j_start + int(array_len)
        tag_j = j_start
        # 品种比例
        # true_value = 0
        # false_value = 0
        ldict1 = {}
        ldict2 = {}
        for mark_tmp in mark_list:
            # 上限
            coef_df1 = coef_df.copy()
            mark_tmp_top = mark_tmp[0]
            exec('true_value = 100 - ul_{}'.format(mark_tmp), locals(), ldict1)
            true_value = ldict1["true_value"]
            # print(true_value)
            exec('false_value = - ul_{}'.format(mark_tmp), locals(), ldict1)
            false_value = ldict1["false_value"]
            # print(false_value)

            # exec('true_value = 100 - ul_{}'.format(mark_tmp))
            # exec('false_value = - ul_{}'.format(mark_tmp))

            def __cal_coef(x):
                if x.mark == mark_tmp:
                    rst = true_value
                elif x.mark != mark_tmp and x.mark[0] == mark_tmp_top:
                    rst = false_value
                else:
                    rst = 0
                return rst

            coef_df1['coef'] = coef_df1.apply(lambda x: __cal_coef(x), axis=1)
            exec("y{} = array([[0]*array_len],dtype=float)".format(j_start))
            for index, row in coef_df1.iterrows():
                exec("y{}[0, index] = row['coef']".format(j_start))
            exec("m{} =  array([0])".format(j_start))
            exec("n{} =  array([0])".format(j_start))
            dict_canshu['编号'] = j_start
            dict_canshu['参数名'] = '品种比例上限'
            if mark_tmp[0] == '1':
                buzhou_tmp = '喷吹煤'
            elif mark_tmp[0] == '2':
                buzhou_tmp = '发电煤'
            elif mark_tmp[0] == '3':
                buzhou_tmp = '烧结煤'
            dict_canshu['步骤'] = buzhou_tmp
            dict_canshu['mark'] = mark_tmp
            new_row = pd.Series(dict_canshu)
            canshu_df = canshu_df.append(new_row, ignore_index=True)
            dict_canshu = {}
            j_start = j_start + 1
            # 下限
            coef_df1 = coef_df.copy()
            mark_tmp_top = mark_tmp[0]
            exec('true_value = ll_{} - 100'.format(mark_tmp), locals(), ldict2)
            true_value = ldict2["true_value"]
            # print(true_value)
            exec('false_value = ll_{}'.format(mark_tmp), locals(), ldict2)
            false_value = ldict2["false_value"]
            # print(false_value)

            # exec('true_value = ll_{} - 100'.format(mark_tmp))
            # exec('false_value = ll_{}'.format(mark_tmp))

            def __cal_coef(x):
                if x.mark == mark_tmp:
                    rst = true_value
                elif x.mark != mark_tmp and x.mark[0] == mark_tmp_top:
                    rst = false_value
                else:
                    rst = 0
                return rst

            coef_df1['coef'] = coef_df1.apply(lambda x: __cal_coef(x), axis=1)
            exec("y{} = array([[0]*array_len],dtype=float)".format(j_start))
            for index, row in coef_df1.iterrows():
                exec("y{}[0, index] = row['coef']".format(j_start))
            exec("m{} =  array([0])".format(j_start))
            exec("n{} =  array([0])".format(j_start))
            dict_canshu['编号'] = j_start
            dict_canshu['参数名'] = '品种比例下限'
            if mark_tmp[0] == '1':
                buzhou_tmp = '喷吹煤'
            elif mark_tmp[0] == '2':
                buzhou_tmp = '发电煤'
            elif mark_tmp[0] == '3':
                buzhou_tmp = '烧结煤'
            dict_canshu['步骤'] = buzhou_tmp
            dict_canshu['mark'] = mark_tmp
            new_row = pd.Series(dict_canshu)
            canshu_df = canshu_df.append(new_row, ignore_index=True)
            dict_canshu = {}
            j_start = j_start + 1
        # 性状比例
        var_list = var_df['group'].to_list()
        ldict3 = {}
        ldict4 = {}
        for var_tmp in var_list:
            # 上限
            coef_df1 = coef_df.copy()
            exec('true_value = 100 - ul_{}'.format(var_tmp), locals(), ldict3)
            true_value = ldict3["true_value"]
            # print(true_value)
            exec('false_value = - ul_{}'.format(var_tmp), locals(), ldict3)
            false_value = ldict3["false_value"]
            # print(false_value)
            # exec('true_value = 100 - ul_{}'.format(var_tmp))
            # exec('false_value = - ul_{}'.format(var_tmp))
            var_tmp_top = var_tmp[0]

            def __cal_coef(x):
                if x.mark[0:3] == var_tmp:
                    rst = true_value
                elif x.mark[0:3] != var_tmp and x.mark[0] == var_tmp_top:
                    rst = false_value
                else:
                    rst = 0
                return rst

            coef_df1['coef'] = coef_df1.apply(lambda x: __cal_coef(x), axis=1)
            exec("y{} = array([[0]*array_len],dtype=float)".format(j_start))
            for index, row in coef_df1.iterrows():
                exec("y{}[0, index] = row['coef']".format(j_start))
            exec("m{} =  array([0])".format(j_start))
            exec("n{} =  array([0])".format(j_start))
            dict_canshu['编号'] = j_start
            dict_canshu['参数名'] = '性状比例上限'
            if var_tmp[0] == '1':
                buzhou_tmp = '喷吹煤'
            elif var_tmp[0] == '2':
                buzhou_tmp = '发电煤'
            elif var_tmp[0] == '3':
                buzhou_tmp = '烧结煤'
            dict_canshu['步骤'] = buzhou_tmp
            dict_canshu['group'] = var_tmp
            new_row = pd.Series(dict_canshu)
            canshu_df = canshu_df.append(new_row, ignore_index=True)
            dict_canshu = {}
            j_start = j_start + 1
            # 下限
            coef_df1 = coef_df.copy()
            exec('true_value = ll_{} - 100'.format(var_tmp), locals(), ldict4)
            true_value = ldict4["true_value"]
            # print(true_value)
            exec('false_value = ll_{}'.format(var_tmp), locals(), ldict4)
            false_value = ldict4["false_value"]
            # print(false_value)
            # exec('true_value = ll_{} - 100'.format(var_tmp))
            # exec('false_value = ll_{}'.format(var_tmp))
            var_tmp_top = var_tmp[0]

            def __cal_coef(x):
                if x.mark[0:3] == var_tmp:
                    rst = true_value
                elif x.mark[0:3] != var_tmp and x.mark[0] == var_tmp_top:
                    rst = false_value
                else:
                    rst = 0
                return rst

            coef_df1['coef'] = coef_df1.apply(lambda x: __cal_coef(x), axis=1)
            exec("y{} = array([[0]*array_len],dtype=float)".format(j_start))
            for index, row in coef_df1.iterrows():
                exec("y{}[0, index] = row['coef']".format(j_start))
            exec("m{} =  array([0])".format(j_start))
            exec("n{} =  array([0])".format(j_start))
            dict_canshu['编号'] = j_start
            dict_canshu['参数名'] = '性状比例下限'
            if var_tmp[0] == '1':
                buzhou_tmp = '喷吹煤'
            elif var_tmp[0] == '2':
                buzhou_tmp = '发电煤'
            elif var_tmp[0] == '3':
                buzhou_tmp = '烧结煤'
            dict_canshu['步骤'] = buzhou_tmp
            dict_canshu['group'] = var_tmp
            new_row = pd.Series(dict_canshu)
            canshu_df = canshu_df.append(new_row, ignore_index=True)
            dict_canshu = {}
            j_start = j_start + 1
        # 煤质上下限
        meizhi_list = ['shui', 'hui', 'huifa', 'liu', 'gu', 'mo', 're', 'cc']
        meizhi_list_fadian = ['shui', 'hui', 'huifa', 'liu', 'gu', 're', 'cc']
        # 喷吹煤
        big_var_tmp = 'penchui'
        for meizhi_tmp in meizhi_list:
            coef_df1 = coef_df.copy()
            # 上限
            exec("y{} = array([[0]*array_len],dtype=float)".format(j_start))
            for index, row in coef_df1.iterrows():
                mark_tmp = row['mark']
                mark_tmp_top = mark_tmp[0]
                if mark_tmp_top == '1':
                    exec("y{}[0, index] = {}_{} - {}_{}_ul".format(j_start, meizhi_tmp, mark_tmp, big_var_tmp,
                                                                   meizhi_tmp))
            exec("m{} =  array([0])".format(j_start))
            exec("n{} =  array([0])".format(j_start))
            dict_canshu['编号'] = j_start
            dict_canshu['参数名'] = '煤质上限'
            dict_canshu['步骤'] = '煤质上下限'
            dict_canshu['big_var'] = '喷吹煤'
            dict_canshu['meizhi'] = meizhi_tmp
            new_row = pd.Series(dict_canshu)
            canshu_df = canshu_df.append(new_row, ignore_index=True)
            dict_canshu = {}
            j_start = j_start + 1
            # 下限
            exec("y{} = array([[0]*array_len],dtype=float)".format(j_start))
            for index, row in coef_df1.iterrows():
                mark_tmp = row['mark']
                mark_tmp_top = mark_tmp[0]
                if mark_tmp_top == '1':
                    exec("y{}[0, index] = {}_{}_ll - {}_{}".format(j_start, big_var_tmp, meizhi_tmp, meizhi_tmp,
                                                                   mark_tmp))
            exec("m{} =  array([0])".format(j_start))
            exec("n{} =  array([0])".format(j_start))
            dict_canshu['编号'] = j_start
            dict_canshu['参数名'] = '煤质下限'
            dict_canshu['步骤'] = '煤质上下限'
            dict_canshu['big_var'] = '喷吹煤'
            dict_canshu['meizhi'] = meizhi_tmp
            new_row = pd.Series(dict_canshu)
            canshu_df = canshu_df.append(new_row, ignore_index=True)
            dict_canshu = {}
            j_start = j_start + 1
        # 发电煤
        big_var_tmp = 'fadian'
        for meizhi_tmp in meizhi_list_fadian:
            coef_df1 = coef_df.copy()
            # 上限
            exec("y{} = array([[0]*array_len],dtype=float)".format(j_start))
            for index, row in coef_df1.iterrows():
                mark_tmp = row['mark']
                mark_tmp_top = mark_tmp[0]
                if mark_tmp_top == '2':
                    exec("y{}[0, index] = {}_{} - {}_{}_ul".format(j_start, meizhi_tmp, mark_tmp, big_var_tmp,
                                                                   meizhi_tmp))
            exec("m{} =  array([0])".format(j_start))
            exec("n{} =  array([0])".format(j_start))
            dict_canshu['编号'] = j_start
            dict_canshu['参数名'] = '煤质上限'
            dict_canshu['步骤'] = '煤质上下限'
            dict_canshu['big_var'] = '发电煤'
            dict_canshu['meizhi'] = meizhi_tmp
            new_row = pd.Series(dict_canshu)
            canshu_df = canshu_df.append(new_row, ignore_index=True)
            dict_canshu = {}
            j_start = j_start + 1
            # 下限
            exec("y{} = array([[0]*array_len],dtype=float)".format(j_start))
            for index, row in coef_df1.iterrows():
                mark_tmp = row['mark']
                mark_tmp_top = mark_tmp[0]
                if mark_tmp_top == '2':
                    exec("y{}[0, index] = {}_{}_ll - {}_{}".format(j_start, big_var_tmp, meizhi_tmp, meizhi_tmp,
                                                                   mark_tmp))
            exec("m{} =  array([0])".format(j_start))
            exec("n{} =  array([0])".format(j_start))
            dict_canshu['编号'] = j_start
            dict_canshu['参数名'] = '煤质下限'
            dict_canshu['步骤'] = '煤质上下限'
            dict_canshu['big_var'] = '发电煤'
            dict_canshu['meizhi'] = meizhi_tmp
            new_row = pd.Series(dict_canshu)
            canshu_df = canshu_df.append(new_row, ignore_index=True)
            dict_canshu = {}
            j_start = j_start + 1
        # 烧结煤
        big_var_tmp = 'shaojie'
        for meizhi_tmp in meizhi_list:
            coef_df1 = coef_df.copy()
            # 上限
            exec("y{} = array([[0]*array_len],dtype=float)".format(j_start))
            for index, row in coef_df1.iterrows():
                mark_tmp = row['mark']
                mark_tmp_top = mark_tmp[0]
                if mark_tmp_top == '3':
                    exec("y{}[0, index] = {}_{} - {}_{}_ul".format(j_start, meizhi_tmp, mark_tmp, big_var_tmp,
                                                                   meizhi_tmp))
            exec("m{} =  array([0])".format(j_start))
            exec("n{} =  array([0])".format(j_start))
            dict_canshu['编号'] = j_start
            dict_canshu['参数名'] = '煤质上限'
            dict_canshu['步骤'] = '煤质上下限'
            dict_canshu['big_var'] = '烧结煤'
            dict_canshu['meizhi'] = meizhi_tmp
            new_row = pd.Series(dict_canshu)
            canshu_df = canshu_df.append(new_row, ignore_index=True)
            dict_canshu = {}
            j_start = j_start + 1
            # 下限
            exec("y{} = array([[0]*array_len],dtype=float)".format(j_start))
            for index, row in coef_df1.iterrows():
                mark_tmp = row['mark']
                mark_tmp_top = mark_tmp[0]
                if mark_tmp_top == '3':
                    exec("y{}[0, index] = {}_{}_ll - {}_{}".format(j_start, big_var_tmp, meizhi_tmp, meizhi_tmp,
                                                                   mark_tmp))
            exec("m{} =  array([0])".format(j_start))
            exec("n{} =  array([0])".format(j_start))
            dict_canshu['编号'] = j_start
            dict_canshu['参数名'] = '煤质下限'
            dict_canshu['步骤'] = '煤质上下限'
            dict_canshu['big_var'] = '烧结煤'
            dict_canshu['meizhi'] = meizhi_tmp
            new_row = pd.Series(dict_canshu)
            canshu_df = canshu_df.append(new_row, ignore_index=True)
            dict_canshu = {}
            j_start = j_start + 1
        # print('y生成完毕')
        # 拼接
        y_str = 'y0'
        # yyy = (y0,y0)
        for j in range(1, j_start):
            y_str = y_str + ',' + 'y' + str(j)
        # exec('yyy =({})'.format(y_str))
        exec('yyy =({})'.format(y_str), locals(), ldict)
        yyy = ldict["yyy"]
        # print(yyy)
        Y = np.concatenate(yyy, axis=0)

        m_str = 'm0'
        # mmm = (m0,m0)
        for j in range(1, j_start):
            m_str = m_str + ',' + 'm' + str(j)
        # exec('mmm =({})'.format(m_str))
        exec('mmm =({})'.format(m_str), locals(), ldict)
        mmm = ldict["mmm"]
        # print(mmm)
        M = np.concatenate(mmm, axis=0)

        n_str = 'n0'
        # nnn = (n0,n0)
        for j in range(1, j_start):
            n_str = n_str + ',' + 'n' + str(j)
        # exec('nnn =({})'.format(n_str))
        exec('nnn =({})'.format(n_str), locals(), ldict)
        nnn = ldict["nnn"]
        # print(nnn)
        N = np.concatenate(nnn, axis=0)

        # print('finish')
        c_str = ''
        ldict5 = {}

        # c = array([[1] * array_len], dtype=float)

        for mark_tmp in mark_list:
            if mark_tmp == '1_1_1':
                c_str = c_str + 'price_1_1_1'
            else:
                # exec("c_str = c_str + ',' + 'price_{}'".format(mark_tmp))
                exec("c_str = c_str + ',' + 'price_{}'".format(mark_tmp), locals(), ldict5)
                c_str = ldict5["c_str"]
                # print(c_str)
        # exec("c = array([{}])".format(c_str))
        exec("c = array([{}])".format(c_str), locals(), ldict)
        c = ldict["c"]
        # print(c)
        # c = array([[1] * array_len], dtype=float)
        e1 = Y
        f1 = M
        ff1 = N
        coef_df1 = coef_df.copy()

        def __cal_coef(x):
            if x.mark[0:3] != '1_3' and x.mark[0] == '1':
                rst = a11
            elif x.mark[0:3] == '1_3':
                rst = a12
            else:
                rst = 0
            return rst

        coef_df1['coef'] = coef_df1.apply(lambda x: __cal_coef(x), axis=1)
        e21 = array([[0] * array_len], dtype=float)
        for index, row in coef_df1.iterrows():
            e21[0, index] = row['coef']
        coef_df1 = coef_df.copy()

        def __cal_coef(x):
            if x.mark[0:3] != '2_3' and x.mark[0] == '2':
                rst = a21
            elif x.mark[0:3] == '2_3':
                rst = a22
            else:
                rst = 0
            return rst

        coef_df1['coef'] = coef_df1.apply(lambda x: __cal_coef(x), axis=1)
        e22 = array([[0] * array_len], dtype=float)
        for index, row in coef_df1.iterrows():
            e22[0, index] = row['coef']
        coef_df1 = coef_df.copy()

        def __cal_coef(x):
            if x.mark[0:3] != '3_2' and x.mark[0] == '3':
                rst = a31
            elif x.mark[0:3] == '3_2':
                rst = a32
            else:
                rst = 0
            return rst

        coef_df1['coef'] = coef_df1.apply(lambda x: __cal_coef(x), axis=1)
        e23 = array([[0] * array_len], dtype=float)
        for index, row in coef_df1.iterrows():
            e23[0, index] = row['coef']
        e222 = (e21, e22, e23)
        e2 = np.concatenate(e222, axis=0)
        f2 = array([b1, b2, b3])
        x = cp.Variable(array_len)
        obj = cp.Minimize(c @ x)
        cons = [e1 @ x <= f1, e2 @ x == f2, x >= 0]
        prob = cp.Problem(obj, cons)
        prob.solve(solver='GLPK_MI', verbose=True)
        # print("最优初始值为:", prob.value)
        # print("最优初始解为：\n", x.value)
        success = 0
        if x.value is None:
            success = 0
            message = '求不出最优方案'
        else:
            success = 1
        # print(success)
            for i in range(0, array_len):
                mark_tmp = mark_list[i]
                value_tmp = abs(x.value[i])
                exec("chushi_x_{} = {}".format(mark_tmp, value_tmp))
            data_waigoujiaofen = data_price[data_price['PROD_DSCR'] == '外购焦粉']
            data_waigoujiaofen = data_waigoujiaofen.reset_index(drop=True)
            price_waigoujiaotan = data_waigoujiaofen.loc[0]['PRICE']
            price_lianjiaomei = data_zhuyao.loc[0]['COKING_COAL_PRICE']
            chushi_z = c @ x.value + WT_waigoujiaotan * price_waigoujiaotan + WT_lianjiaomei * price_lianjiaomei
            Z2 = c @ x.value
            ###粒子初始解构造
            coef_df1 = coef_df.copy()
            # coef_df1['chushi'] = x.value
            coef_df1['chushi'] = abs(x.value)
            pso_coef_df1 = coef_df1[
                (coef_df1['mark'] != '1_3_1') & (coef_df1['mark'] != '2_3_1') & (coef_df1['mark'] != '3_2_1')]
            pso_coef_df1 = pso_coef_df1.reset_index(drop=True)
            # print(pso_coef_df1)

            ######################################
            ############不考虑可供资源的初始解
            cons = [e1 @ x <= ff1, e2 @ x == f2, x >= 0]
            prob = cp.Problem(obj, cons)
            prob.solve(solver='GLPK_MI', verbose=True)
            # print("最优初始值为:", prob.value)
            # print("最优初始解为：\n", x.value)
            success = 0
            if x.value is None:
                success = 0
                message = '求不出最优方案'
            else:
                success = 1
            # print(success)
            for i in range(0, array_len):
                mark_tmp = mark_list[i]
                value_tmp = abs(x.value[i])
                exec("chushi2_x_{} = {}".format(mark_tmp, value_tmp))
            coef_df2 = coef_df.copy()
            coef_df2['chushi'] = abs(x.value)
            pso_coef_df12 = coef_df2[
                (coef_df2['mark'] != '1_3_1') & (coef_df2['mark'] != '2_3_1') & (coef_df2['mark'] != '3_2_1')]
            pso_coef_df12 = pso_coef_df12.reset_index(drop=True)
            # print(pso_coef_df12)

            pso_mark_list = pso_coef_df1['mark'].to_list()
            len_pso_mark = len(pso_mark_list)

            dim = len_pso_mark

            def build_chushi(chushi_n, chushi_value_tmp):
                for i in range(0, array_len):
                    mark_tmp = mark_list[i]
                    coef_df2 = coef_df1[coef_df1['mark'] == mark_tmp]
                    coef_df2 = coef_df2.reset_index(drop=True)
                    chushi_value = coef_df2.loc[0]['chushi']
                    if int(chushi_value_tmp) != int(chushi_value):
                        chushi_value_tmp = chushi_value_tmp
                        # chushi_value_tmp = int(chushi_value_tmp) + diff
                        e24 = array([[0] * array_len], dtype=float)
                        e24[0, i] = 1
                        e222 = (e21, e22, e23, e24)
                        e2 = np.concatenate(e222, axis=0)
                        f2 = array([b1, b2, b3, chushi_value_tmp])
                        x = cp.Variable(array_len)
                        obj = cp.Minimize(c @ x)
                        cons = [e1 @ x <= f1, e2 @ x == f2, x >= 0]
                        prob = cp.Problem(obj, cons)
                        prob.solve(solver='GLPK_MI', verbose=True)
                        success = 0
                        if x.value is None:
                            success = 0
                        else:
                            success = 1
                            chushi_n = chushi_n + 1
                            coef_df1[str(chushi_n)] = abs(x.value)
                return chushi_n

            def build_chushi2(chushi_n, diff):
                for i in range(0, array_len):
                    mark_tmp = mark_list[i]
                    coef_df2 = coef_df1[coef_df1['mark'] == mark_tmp]
                    coef_df2 = coef_df2.reset_index(drop=True)
                    chushi_value_tmp = coef_df2.loc[0]['chushi']
                    chushi_value_tmp = int(chushi_value_tmp) + diff
                    if chushi_value_tmp >= 0:
                        e24 = array([[0] * array_len], dtype=float)
                        e24[0, i] = 1
                        e222 = (e21, e22, e23, e24)
                        e2 = np.concatenate(e222, axis=0)
                        f2 = array([b1, b2, b3, chushi_value_tmp])
                        x = cp.Variable(array_len)
                        obj = cp.Minimize(c @ x)
                        cons = [e1 @ x <= f1, e2 @ x == f2, x >= 0]
                        prob = cp.Problem(obj, cons)
                        prob.solve(solver='GLPK_MI', verbose=True)
                        success = 0
                        if x.value is None:
                            success = 0
                        else:
                            success = 1
                            chushi_n = chushi_n + 1
                            coef_df1[str(chushi_n)] = abs(x.value)
                return chushi_n

            chushi_n = 0
            # 置0初始解
            for i in range(0, 11):
                chushi_value_tmp = i * 5
                chushi_n = build_chushi(chushi_n, chushi_value_tmp)
            for i in range(1, 20):
                chushi_n = build_chushi2(chushi_n, i)
                chushi_n = build_chushi2(chushi_n, -i)
                if chushi_n >= 3 * size:
                    break
            # print(chushi_n)

            max_constant = kongmeizhibiao - WT_lianjiaomei
            low = [0] * len_pso_mark
            up = [max_constant] * len_pso_mark
            for i in range(0, len_pso_mark):
                pso_mark_tmp = pso_mark_list[i]
                exec('up[i] = min(max_constant,kegongziyuan_{})'.format(pso_mark_tmp))
            # print(up)
            bound = []  # 变量的约束范围
            bound.append(low)
            bound.append(up)
            # X = np.random.uniform(0, 1, size=(size, dim))
            coef_df1 = coef_df1[
                (coef_df1['mark'] != '1_3_1') & (coef_df1['mark'] != '2_3_1') & (coef_df1['mark'] != '3_2_1')]
            coef_df1 = coef_df1.reset_index(drop=True)
            coef_df1.drop(['mark'], axis=1, inplace=True)
            # coef_df1.rename(columns={'chushi': '0'}, inplace=True)
            coef_df1.drop(['chushi'], axis=1, inplace=True)

            X_df = coef_df1.T
            X_df_sample = X_df.sample(n=size)
            X_df_sample = X_df_sample.reset_index(drop=True)

            XNd = X_df_sample.values

            # 初始化种群的各个粒子的速度
            V = np.random.uniform(-max_vel, max_vel, size=(size, dim))
            pso_c_str = ''
            ldict6 = {}
            # pso_c = array([[1] * len(pso_mark_list)], dtype=float)
            for pso_mark_tmp in pso_mark_list:
                if pso_mark_tmp == '1_1_1':
                    pso_c_str = pso_c_str + 'price_1_1_1'
                else:
                    # exec("pso_c_str = pso_c_str + ',' + 'price_{}'".format(mark_tmp))
                    exec("pso_c_str = pso_c_str + ',' + 'price_{}'".format(mark_tmp), locals(), ldict6)
                    pso_c_str = ldict6["pso_c_str"]
                    # print(pso_c_str)
            # exec("pso_c = array([{}])".format(pso_c_str))
            exec("pso_c = array([{}])".format(pso_c_str), locals(), ldict)
            pso_c = ldict["pso_c"]
            # print(pso_c)

            def calc_f(X):
                x_tmp = X
                coef_df2 = coef_df.copy()
                pso_coef_df2 = coef_df2[
                    (coef_df2['mark'] != '1_3_1') & (coef_df2['mark'] != '2_3_1') & (coef_df2['mark'] != '3_2_1')]
                pso_coef_df2 = pso_coef_df2.reset_index(drop=True)
                pso_coef_df2['wt'] = x_tmp
                pso_coef_df2['group'] = pso_coef_df2['mark'].str[0:3]
                group1_df = pso_coef_df2[(pso_coef_df2['group'] == '1_1') | (pso_coef_df2['group'] == '1_2')]
                group1_sum_wt = group1_df['wt'].sum()
                group2_df = pso_coef_df2[(pso_coef_df2['group'] == '2_1') | (pso_coef_df2['group'] == '2_2')]
                group2_sum_wt = group2_df['wt'].sum()
                group3_df = pso_coef_df2[(pso_coef_df2['group'] == '3_1')]
                group3_sum_wt = group3_df['wt'].sum()
                group4_df = pso_coef_df2[(pso_coef_df2['group'] == '1_3')]
                group4_sum_wt = group4_df['wt'].sum()
                group5_df = pso_coef_df2[(pso_coef_df2['group'] == '2_3')]
                group5_sum_wt = group5_df['wt'].sum()
                group6_df = pso_coef_df2[(pso_coef_df2['group'] == '3_2') | (pso_coef_df2['group'] == '3_3')]
                group6_sum_wt = group6_df['wt'].sum()
                WT_gaolulantan = (b1 - a11 * group1_sum_wt) / a12
                wt_1_3_1 = WT_gaolulantan - group4_sum_wt
                if wt_1_3_1 < 0:
                    wt_1_3_1 = 0
                WT_dianchanglantan = (b2 - a21 * group2_sum_wt) / a22
                wt_2_3_1 = WT_dianchanglantan - group5_sum_wt
                if wt_2_3_1 < 0:
                    wt_2_3_1 = 0
                WT_shaojiejiaofen = (b3 - a31 * group3_sum_wt) / a32
                wt_3_2_1 = WT_shaojiejiaofen - group6_sum_wt
                if wt_3_2_1 < 0:
                    wt_3_2_1 = 0
                pprice_1_3_1 = df3_price.loc[df3_price['mark'] == '1_3_1', 'PRICE'].item()
                # print(pprice_1_3_1)
                pprice_2_3_1 = df3_price.loc[df3_price['mark'] == '2_3_1', 'PRICE'].item()
                # print(pprice_2_3_1)
                pprice_3_2_1 = df3_price.loc[df3_price['mark'] == '3_2_1', 'PRICE'].item()
                # print(pprice_3_2_1)
                Z = pso_c @ x_tmp + wt_1_3_1 * pprice_1_3_1 + wt_2_3_1 * pprice_2_3_1 + wt_3_2_1 * pprice_3_2_1
                return Z

            Z = calc_f(XNd[0])
            #########################拼接PSO不等式约束
            # 1_3_1
            pso_coef_df2 = pso_coef_df1.copy()
            pso_coef_df2['group'] = pso_coef_df2['mark'].str[0:3]

            def __cal_coef(x):
                if x.group == '1_3':
                    rst = 1
                elif x.group == '1_1' or x.group == '1_2':
                    rst = 2
                else:
                    rst = 0
                return rst

            pso_coef_df2['coef'] = pso_coef_df2.apply(lambda x: __cal_coef(x), axis=1)
            cf_str = '(b1- a11 * (0'
            for index, row in pso_coef_df2.iterrows():
                if row['coef'] == 2:
                    cf_str = cf_str + '+ x[' + str(index) + ']'
            cf_str = cf_str + ')) / a12'
            for index, row in pso_coef_df2.iterrows():
                if row['coef'] == 1:
                    cf_str = cf_str + '- x[' + str(index) + ']'
            str1 = cf_str
            # 2_3_1
            pso_coef_df2 = pso_coef_df1.copy()
            pso_coef_df2['group'] = pso_coef_df2['mark'].str[0:3]

            def __cal_coef(x):
                if x.group == '2_3':
                    rst = 1
                elif x.group == '2_1' or x.group == '2_2':
                    rst = 2
                else:
                    rst = 0
                return rst

            pso_coef_df2['coef'] = pso_coef_df2.apply(lambda x: __cal_coef(x), axis=1)
            cf_str = '(b2- a21 * (0'
            for index, row in pso_coef_df2.iterrows():
                if row['coef'] == 2:
                    cf_str = cf_str + '+ x[' + str(index) + ']'
            cf_str = cf_str + ')) / a22'
            for index, row in pso_coef_df2.iterrows():
                if row['coef'] == 1:
                    cf_str = cf_str + '- x[' + str(index) + ']'
            str2 = cf_str
            # 3_2_1
            pso_coef_df2 = pso_coef_df1.copy()
            pso_coef_df2['group'] = pso_coef_df2['mark'].str[0:3]

            def __cal_coef(x):
                if x.group == '3_2' or x.group == '3_3':
                    rst = 1
                elif x.group == '3_1':
                    rst = 2
                else:
                    rst = 0
                return rst

            pso_coef_df2['coef'] = pso_coef_df2.apply(lambda x: __cal_coef(x), axis=1)
            cf_str = '(b3- a31 * (0'
            for index, row in pso_coef_df2.iterrows():
                if row['coef'] == 2:
                    cf_str = cf_str + '+ x[' + str(index) + ']'
            cf_str = cf_str + ')) / a32'
            for index, row in pso_coef_df2.iterrows():
                if row['coef'] == 1:
                    cf_str = cf_str + '- x[' + str(index) + ']'
            str3 = cf_str
            # 构建mark以及对应字符串
            mark_str_df = coef_df.copy()
            pso_mark_df = pso_coef_df1.copy()
            pso_mark_df.drop(['chushi'], axis=1, inplace=True)
            pso_mark_df = pso_mark_df.reset_index(drop=True)
            pso_mark_df = pso_mark_df.reset_index(drop=False)
            pso_mark_df.rename(columns={'index': 'rank'}, inplace=True)
            pso_mark_df['rank0'] = pso_mark_df['rank'].astype(int)
            pso_mark_df.drop(['rank'], axis=1, inplace=True)

            def __cal_coef(x):
                rst = 'x[' + str(x.rank0) + ']'
                return rst

            pso_mark_df['pso_str'] = pso_mark_df.apply(lambda x: __cal_coef(x), axis=1)
            pso_mark_df['pso'] = 1
            v = ['mark']
            mark_str_df = pd.merge(mark_str_df, pso_mark_df, on=v, how='left')

            def __cal_str(x):
                if x.mark == '1_3_1':
                    rst = '(' + str1 + ')'
                elif x.mark == '2_3_1':
                    rst = '(' + str2 + ')'
                elif x.mark == '3_2_1':
                    rst = '(' + str3 + ')'
                else:
                    rst = x.pso_str
                return rst

            mark_str_df['pso_str_final'] = mark_str_df.apply(lambda x: __cal_str(x), axis=1)

            k_start = 0
            # 必要条件，控煤指标
            cf0_str = 'lambda x: (kongmeizhibiao - WT_lianjiaomei) '
            pso_coef_df2 = pso_coef_df1.copy()
            pso_coef_df2['group'] = pso_coef_df2['mark'].str[0:3]

            def __cal_coef(x):
                if x.group != '1_3' and x.group != '2_3' and x.group != '3_2' and x.group != '3_3':
                    rst = 1
                else:
                    rst = 0
                return rst

            pso_coef_df2['coef'] = pso_coef_df2.apply(lambda x: __cal_coef(x), axis=1)
            for index, row in pso_coef_df2.iterrows():
                if row['coef'] == 1:
                    cf0_str = cf0_str + '+ x[' + str(index) + ']'
            # print(cf0_str)
            k_start = k_start + 1
            # 三个兰炭的控煤指标max与min约束
            # 下限
            # 1_3_1
            cf_str = 'lambda x: 0 - ' + '(' + str1 + ')'
            exec("cf{}_str = cf_str".format(k_start))
            k_start = k_start + 1
            # 2_3_1
            cf_str = 'lambda x: 0 - ' + '(' + str2 + ')'
            exec("cf{}_str = cf_str".format(k_start))
            k_start = k_start + 1
            # 3_2_1
            cf_str = 'lambda x: 0 - ' + '(' + str3 + ')'
            exec("cf{}_str = cf_str".format(k_start))
            k_start = k_start + 1
            # 上限可供资源
            # 1_3_1
            cf_str = 'lambda x: ' + '(' + str1 + ')' + ' - kegongziyuan_1_3_1 '
            exec("cf{}_str = cf_str".format(k_start))
            k_start = k_start + 1
            # 2_3_1
            cf_str = 'lambda x: ' + '(' + str2 + ')' + ' - kegongziyuan_2_3_1 '
            exec("cf{}_str = cf_str".format(k_start))
            k_start = k_start + 1
            # 3_2_1
            cf_str = 'lambda x: ' + '(' + str3 + ')' + ' - kegongziyuan_3_2_1 '
            exec("cf{}_str = cf_str".format(k_start))
            k_start = k_start + 1
            # 比例上下限
            for j in range(tag_j, j_start):
                mark_str_df1 = mark_str_df.copy()
                exec("mark_str_df1['coef'] = y{}.T".format(j))
                cf_str = 'lambda x: '
                for index, row in mark_str_df1.iterrows():
                    cf_str = cf_str + '+' + str(row['coef']) + '*' + str(row['pso_str_final'])
                # print(j)
                exec("cf{}_str = cf_str".format(k_start))
                k_start = k_start + 1
            constraint_ueq_str = '('
            ldict7 = {}
            for k in range(0, k_start):
                # exec("constraint_ueq_str = constraint_ueq_str + cf{}_str + ','".format(k))
                exec("constraint_ueq_str = constraint_ueq_str + cf{}_str + ','".format(k), locals(), ldict7)
                constraint_ueq_str = ldict7["constraint_ueq_str"]
                # print(constraint_ueq_str)
            # constraint_ueq = (lambda x: -x[0],)
            constraint_ueq_str = constraint_ueq_str + ')'
            # exec("constraint_ueq = {}".format(constraint_ueq_str))
            exec("constraint_ueq = {}".format(constraint_ueq_str), locals(), ldict)
            constraint_ueq = ldict["constraint_ueq"]
            # print(constraint_ueq)


            def calc_f2(X, scheme_name):
                x_tmp = X
                coef_df2 = coef_df.copy()
                pso_coef_df2 = coef_df2[
                    (coef_df2['mark'] != '1_3_1') & (coef_df2['mark'] != '2_3_1') & (coef_df2['mark'] != '3_2_1')]
                pso_coef_df2 = pso_coef_df2.reset_index(drop=True)
                pso_coef_df2['wt'] = x_tmp
                pso_coef_df2['group'] = pso_coef_df2['mark'].str[0:3]
                group1_df = pso_coef_df2[(pso_coef_df2['group'] == '1_1') | (pso_coef_df2['group'] == '1_2')]
                group1_sum_wt = group1_df['wt'].sum()
                group2_df = pso_coef_df2[(pso_coef_df2['group'] == '2_1') | (pso_coef_df2['group'] == '2_2')]
                group2_sum_wt = group2_df['wt'].sum()
                group3_df = pso_coef_df2[(pso_coef_df2['group'] == '3_1')]
                group3_sum_wt = group3_df['wt'].sum()
                group4_df = pso_coef_df2[(pso_coef_df2['group'] == '1_3')]
                group4_sum_wt = group4_df['wt'].sum()
                group5_df = pso_coef_df2[(pso_coef_df2['group'] == '2_3')]
                group5_sum_wt = group5_df['wt'].sum()
                group6_df = pso_coef_df2[(pso_coef_df2['group'] == '3_2') | (pso_coef_df2['group'] == '3_3')]
                group6_sum_wt = group6_df['wt'].sum()
                WT_gaolulantan = (b1 - a11 * group1_sum_wt) / a12
                wt_1_3_1 = WT_gaolulantan - group4_sum_wt
                if wt_1_3_1 < 0:
                    wt_1_3_1 = 0
                WT_dianchanglantan = (b2 - a21 * group2_sum_wt) / a22
                wt_2_3_1 = WT_dianchanglantan - group5_sum_wt
                if wt_2_3_1 < 0:
                    wt_2_3_1 = 0
                WT_shaojiejiaofen = (b3 - a31 * group3_sum_wt) / a32
                wt_3_2_1 = WT_shaojiejiaofen - group6_sum_wt
                if wt_3_2_1 < 0:
                    wt_3_2_1 = 0
                pso_coef_df2.drop(['group'], axis=1, inplace=True)
                dict = {}
                dict['mark'] = '1_3_1'
                dict['wt'] = wt_1_3_1
                new_row = pd.Series(dict)
                pso_coef_df2 = pso_coef_df2.append(new_row, ignore_index=True)
                dict['mark'] = '2_3_1'
                dict['wt'] = wt_2_3_1
                new_row = pd.Series(dict)
                pso_coef_df2 = pso_coef_df2.append(new_row, ignore_index=True)
                dict['mark'] = '3_2_1'
                dict['wt'] = wt_3_2_1
                new_row = pd.Series(dict)
                pso_coef_df2 = pso_coef_df2.append(new_row, ignore_index=True)
                v = ['mark']
                df_out1 = pd.merge(data0, pso_coef_df2, on=v, how='left')
                v = ['PROD_DSCR']
                df_out1 = pd.merge(df_out1, data_price, on=v, how='left')
                df_out1.drop(['index_old'], axis=1, inplace=True)
                df_out1.drop(['pinzhong'], axis=1, inplace=True)
                df_out1.drop(['xingzhuang'], axis=1, inplace=True)
                df_out1.drop(['pinming'], axis=1, inplace=True)
                df_out1.drop(['mark'], axis=1, inplace=True)
                df_out1['FLAG'] = '明细'
                df_out1.rename(columns={'PRICE': 'UNIT_PRICE'}, inplace=True)
                df_out1.rename(columns={'wt': 'WT'}, inplace=True)
                df_out1['TOTAL_PRICE'] = df_out1['WT'] * df_out1['UNIT_PRICE']
                df_out0 = df_out1.copy()
                df_out0.drop(['group'], axis=1, inplace=True)
                group1_df1 = df_out1[(df_out1['group'] == '1_1') | (df_out1['group'] == '1_2')]
                group1_sum_wt_NEW = group1_df1['WT'].sum()
                group1_sum_price_NEW = group1_df1['TOTAL_PRICE'].sum()
                group2_df1 = df_out1[(df_out1['group'] == '2_1') | (df_out1['group'] == '2_2')]
                group2_sum_wt_NEW = group2_df1['WT'].sum()
                group2_sum_price_NEW = group2_df1['TOTAL_PRICE'].sum()
                group3_df1 = df_out1[(df_out1['group'] == '3_1')]
                group3_sum_wt_NEW = group3_df1['WT'].sum()
                group3_sum_price_NEW = group3_df1['TOTAL_PRICE'].sum()
                group4_df1 = df_out1[(df_out1['group'] == '1_3')]
                group4_sum_wt_NEW = group4_df1['WT'].sum()
                group4_sum_price_NEW = group4_df1['TOTAL_PRICE'].sum()
                group5_df1 = df_out1[(df_out1['group'] == '2_3')]
                group5_sum_wt_NEW = group5_df1['WT'].sum()
                group5_sum_price_NEW = group5_df1['TOTAL_PRICE'].sum()
                group6_df1 = df_out1[(df_out1['group'] == '3_2') | (df_out1['group'] == '3_3')]
                group6_sum_wt_NEW = group6_df1['WT'].sum()
                group6_sum_price_NEW = group6_df1['TOTAL_PRICE'].sum()
                dict = {}
                dict['FLAG'] = '统计'
                dict['BIG_VAR'] = '喷吹煤'
                dict['VAR'] = '喷吹煤'
                dict['WT'] = group1_sum_wt_NEW
                if group1_sum_wt_NEW == 0:
                    dict['UNIT_PRICE'] = None
                else:
                    dict['UNIT_PRICE'] = group1_sum_price_NEW / group1_sum_wt_NEW
                dict['TOTAL_PRICE'] = group1_sum_price_NEW
                new_row = pd.Series(dict)
                df_out0 = df_out0.append(new_row, ignore_index=True)
                dict['FLAG'] = '统计'
                dict['BIG_VAR'] = '炼焦煤'
                dict['VAR'] = '炼焦煤'
                dict['WT'] = WT_lianjiaomei
                dict['UNIT_PRICE'] = price_lianjiaomei
                dict['TOTAL_PRICE'] = WT_lianjiaomei * price_lianjiaomei
                new_row = pd.Series(dict)
                df_out0 = df_out0.append(new_row, ignore_index=True)
                dict['FLAG'] = '统计'
                dict['BIG_VAR'] = '发电煤'
                dict['VAR'] = '发电煤'
                dict['WT'] = group2_sum_wt_NEW
                if group2_sum_wt_NEW == 0:
                    dict['UNIT_PRICE'] = None
                else:
                    dict['UNIT_PRICE'] = group2_sum_price_NEW / group2_sum_wt_NEW
                dict['TOTAL_PRICE'] = group2_sum_price_NEW
                new_row = pd.Series(dict)
                df_out0 = df_out0.append(new_row, ignore_index=True)
                dict['FLAG'] = '统计'
                dict['BIG_VAR'] = '烧结煤'
                dict['VAR'] = '烧结煤'
                dict['WT'] = group3_sum_wt_NEW
                if group3_sum_wt_NEW == 0:
                    dict['UNIT_PRICE'] = None
                else:
                    dict['UNIT_PRICE'] = group3_sum_price_NEW / group3_sum_wt_NEW
                dict['TOTAL_PRICE'] = group3_sum_price_NEW
                new_row = pd.Series(dict)
                df_out0 = df_out0.append(new_row, ignore_index=True)
                dict['FLAG'] = '统计'
                dict['BIG_VAR'] = '喷吹煤'
                dict['VAR'] = '高炉兰炭'
                dict['WT'] = group4_sum_wt_NEW
                if group4_sum_wt_NEW == 0:
                    dict['UNIT_PRICE'] = None
                else:
                    dict['UNIT_PRICE'] = group4_sum_price_NEW / group4_sum_wt_NEW
                dict['TOTAL_PRICE'] = group4_sum_price_NEW
                new_row = pd.Series(dict)
                df_out0 = df_out0.append(new_row, ignore_index=True)
                dict['FLAG'] = '统计'
                dict['BIG_VAR'] = '炼焦煤'
                dict['VAR'] = '外购焦炭'
                dict['WT'] = WT_waigoujiaotan
                dict['UNIT_PRICE'] = price_waigoujiaotan
                dict['TOTAL_PRICE'] = WT_waigoujiaotan * price_waigoujiaotan
                new_row = pd.Series(dict)
                df_out0 = df_out0.append(new_row, ignore_index=True)
                dict['FLAG'] = '统计'
                dict['BIG_VAR'] = '发电煤'
                dict['VAR'] = '电厂兰炭'
                dict['WT'] = group5_sum_wt_NEW
                if group5_sum_wt_NEW == 0:
                    dict['UNIT_PRICE'] = None
                else:
                    dict['UNIT_PRICE'] = group5_sum_price_NEW / group5_sum_wt_NEW
                dict['TOTAL_PRICE'] = group5_sum_price_NEW
                new_row = pd.Series(dict)
                df_out0 = df_out0.append(new_row, ignore_index=True)
                dict['FLAG'] = '统计'
                dict['BIG_VAR'] = '烧结煤'
                dict['VAR'] = '烧结焦粉'
                dict['WT'] = group6_sum_wt_NEW
                if group6_sum_wt_NEW == 0:
                    dict['UNIT_PRICE'] = None
                else:
                    dict['UNIT_PRICE'] = group6_sum_price_NEW / group6_sum_wt_NEW
                dict['TOTAL_PRICE'] = group6_sum_price_NEW
                new_row = pd.Series(dict)
                df_out0 = df_out0.append(new_row, ignore_index=True)
                dict['FLAG'] = '统计'
                dict['BIG_VAR'] = '喷吹煤'
                dict['VAR'] = '合计'
                dict['WT'] = group1_sum_wt_NEW + group4_sum_wt_NEW
                if group1_sum_wt_NEW + group4_sum_wt_NEW == 0:
                    dict['UNIT_PRICE'] = None
                else:
                    dict['UNIT_PRICE'] = (group1_sum_price_NEW + group4_sum_price_NEW) / (
                                group1_sum_wt_NEW + group4_sum_wt_NEW)
                dict['TOTAL_PRICE'] = group1_sum_price_NEW + group4_sum_price_NEW
                new_row = pd.Series(dict)
                df_out0 = df_out0.append(new_row, ignore_index=True)
                dict['FLAG'] = '统计'
                dict['BIG_VAR'] = '炼焦煤'
                dict['VAR'] = '合计'
                dict['WT'] = WT_lianjiaomei + WT_waigoujiaotan
                dict['UNIT_PRICE'] = (WT_lianjiaomei * price_lianjiaomei + WT_waigoujiaotan * price_waigoujiaotan) / (
                            WT_lianjiaomei + WT_waigoujiaotan)
                dict['TOTAL_PRICE'] = WT_lianjiaomei * price_lianjiaomei + WT_waigoujiaotan * price_waigoujiaotan
                new_row = pd.Series(dict)
                df_out0 = df_out0.append(new_row, ignore_index=True)
                dict['FLAG'] = '统计'
                dict['BIG_VAR'] = '发电煤'
                dict['VAR'] = '合计'
                dict['WT'] = group2_sum_wt_NEW + group5_sum_wt_NEW
                if group2_sum_wt_NEW + group5_sum_wt_NEW == 0:
                    dict['UNIT_PRICE'] = None
                else:
                    dict['UNIT_PRICE'] = (group2_sum_price_NEW + group5_sum_price_NEW) / (
                                group2_sum_wt_NEW + group5_sum_wt_NEW)
                dict['TOTAL_PRICE'] = group2_sum_price_NEW + group5_sum_price_NEW
                new_row = pd.Series(dict)
                df_out0 = df_out0.append(new_row, ignore_index=True)
                dict['FLAG'] = '统计'
                dict['BIG_VAR'] = '烧结煤'
                dict['VAR'] = '合计'
                dict['WT'] = group3_sum_wt_NEW + group6_sum_wt_NEW
                if group3_sum_wt_NEW + group6_sum_wt_NEW == 0:
                    dict['UNIT_PRICE'] = None
                else:
                    dict['UNIT_PRICE'] = (group3_sum_price_NEW + group6_sum_price_NEW) / (
                                group3_sum_wt_NEW + group6_sum_wt_NEW)
                dict['TOTAL_PRICE'] = group3_sum_price_NEW + group6_sum_price_NEW
                new_row = pd.Series(dict)
                df_out0 = df_out0.append(new_row, ignore_index=True)
                dict['FLAG'] = '统计'
                dict['BIG_VAR'] = '纯煤'
                dict['VAR'] = '合计'
                dict['WT'] = group1_sum_wt_NEW + group2_sum_wt_NEW + group3_sum_wt_NEW + WT_lianjiaomei
                dict['UNIT_PRICE'] = (
                                                 group1_sum_price_NEW + group2_sum_price_NEW + group3_sum_price_NEW + WT_lianjiaomei * price_lianjiaomei) / (
                                                 group1_sum_wt_NEW + group2_sum_wt_NEW + group3_sum_wt_NEW + WT_lianjiaomei)
                dict[
                    'TOTAL_PRICE'] = group1_sum_price_NEW + group2_sum_price_NEW + group3_sum_price_NEW + WT_lianjiaomei * price_lianjiaomei
                new_row = pd.Series(dict)
                df_out0 = df_out0.append(new_row, ignore_index=True)
                dict['FLAG'] = '统计'
                dict['BIG_VAR'] = '替代'
                dict['VAR'] = '合计'
                dict['WT'] = group4_sum_wt_NEW + group5_sum_wt_NEW + group6_sum_wt_NEW + WT_waigoujiaotan
                dict['UNIT_PRICE'] = (
                                                 group4_sum_price_NEW + group5_sum_price_NEW + group6_sum_price_NEW + WT_waigoujiaotan * price_waigoujiaotan) / (
                                                 group4_sum_wt_NEW + group5_sum_wt_NEW + group6_sum_wt_NEW + WT_waigoujiaotan)
                dict[
                    'TOTAL_PRICE'] = group4_sum_price_NEW + group5_sum_price_NEW + group6_sum_price_NEW + WT_waigoujiaotan * price_waigoujiaotan
                new_row = pd.Series(dict)
                df_out0 = df_out0.append(new_row, ignore_index=True)
                dict['FLAG'] = '统计'
                dict['BIG_VAR'] = '合计'
                dict['VAR'] = '合计'
                dict[
                    'WT'] = group1_sum_wt_NEW + group2_sum_wt_NEW + group3_sum_wt_NEW + WT_lianjiaomei + group4_sum_wt_NEW + group5_sum_wt_NEW + group6_sum_wt_NEW + WT_waigoujiaotan
                dict['UNIT_PRICE'] = (
                                                 group1_sum_price_NEW + group2_sum_price_NEW + group3_sum_price_NEW + WT_lianjiaomei * price_lianjiaomei + group4_sum_price_NEW + group5_sum_price_NEW + group6_sum_price_NEW + WT_waigoujiaotan * price_waigoujiaotan) / (
                                                 group1_sum_wt_NEW + group2_sum_wt_NEW + group3_sum_wt_NEW + WT_lianjiaomei + group4_sum_wt_NEW + group5_sum_wt_NEW + group6_sum_wt_NEW + WT_waigoujiaotan)
                dict[
                    'TOTAL_PRICE'] = group1_sum_price_NEW + group2_sum_price_NEW + group3_sum_price_NEW + WT_lianjiaomei * price_lianjiaomei + group4_sum_price_NEW + group5_sum_price_NEW + group6_sum_price_NEW + WT_waigoujiaotan * price_waigoujiaotan
                new_row = pd.Series(dict)
                df_out0 = df_out0.append(new_row, ignore_index=True)
                df_out0['TMPL_NO'] = tmpl_no
                df_out0['SCHEME_NAME'] = scheme_name
                order = ['TMPL_NO', 'SCHEME_NAME', 'FLAG', 'BIG_VAR', 'VAR', 'PROD_DSCR', 'PROD_CODE', 'WT', 'UNIT_PRICE',
                         'TOTAL_PRICE']
                df_out0 = df_out0[order]
                now = datetime.datetime.now()
                now_1 = now.strftime('%Y%m%d%H%M%S')
                df_out0['REC_CREATE_TIME'] = now_1
                df_out0['REC_CREATOR'] = 'g0mazzai'
                df_out0['REC_REVISE_TIME'] = now_1
                df_out0['REC_REVISOR'] = 'g0mazzai'
                df_out0_rounded = df_out0.round(3)
                #####存入到数据库


                df_out0_rounded.to_sql(name='T_ADS_FACT_YLMX_MODEL_SCHEME'.lower(),
                          con=db_conn_mpp,
                          schema='BG00MAZZAI'.lower(),
                          index=False,
                          if_exists='append',
                          chunksize=10000)
                # writer = pd.ExcelWriter(scheme_name +'.xlsx')
                # df_out0_rounded.to_excel(writer, sheet_name='Sheet1', index=False)
                # writer.save()
                # print(df_out0_rounded)
                return df_out0_rounded

            # X = XNd[0]
            # 初始最优解
            sql = " DELETE FROM " \
                  " BG00MAZZAI.T_ADS_FACT_YLMX_MODEL_SCHEME" \
                  " WHERE 1=1 AND TMPL_NO ='%s' " % (tmpl_no)
            db_conn_mpp.execute(sql)
            X_chushi = pso_coef_df1['chushi']
            X_chushi2 = pso_coef_df12['chushi']

            df_out0_rounded0 = calc_f2(X=X_chushi, scheme_name='考虑可供资源')
            df_out0_rounded0b = calc_f2(X=X_chushi2, scheme_name='不考虑可供资源')

            pso = PSO(func=calc_f, n_dim=dim, pop=size, max_iter=iter_num, lb=low, ub=up, w=w, c1=c1, c2=c2
                      , constraint_ueq=constraint_ueq, X=XNd, V=V)
            pso.record_mode = True
            pso.run()
            # print('经过PSO计算得到的最优解：',pso.gbest_x)
            best_x = pso.gbest_x
            # print('此时目标函数值为',calc_f(best_x))
            pbest2 = np.concatenate([pso.pbest_x, pso.pbest_y], axis=1)

            idex = np.lexsort([pbest2[:, 20]])
            sorted_data = pbest2[idex, :]

            best_5 = sorted_data[[0, 1, 2, 3, 4]]
            best_5 = np.delete(best_5, -1, 1)
            # print('最优五组解分别是：')
            # print(best_5[0])
            # print(best_5[1])
            # print(best_5[2])
            # print(best_5[3])
            # print(best_5[4])

            df_out0_rounded1 = calc_f2(X=best_5[0], scheme_name='其他1')
            df_out0_rounded2 = calc_f2(X=best_5[1], scheme_name='其他2')
            df_out0_rounded3 = calc_f2(X=best_5[2], scheme_name='其他3')
            df_out0_rounded4 = calc_f2(X=best_5[3], scheme_name='其他4')
            df_out0_rounded5 = calc_f2(X=best_5[4], scheme_name='其他5')

            # print('finish')

            # elapsed = float((datetime.datetime.now() - start).seconds)
            # print("Time Used 4 All ----->>>> %f seconds" % (elapsed))

            # print('finish')
            message = '最优方案已入库'
        return message